package mc.support.util;

import org.joda.time.DateTime;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA. <br/>
 * Author: francis Yun    <br/>
 * Date: 2013-12-14  <br/>
 */
public final class DateTimeUtil {

    public static final SimpleDateFormat DT_FORMAT = new SimpleDateFormat("yyyyMMdd");
    private DateTimeUtil() {}

    /**
     * expire at tomorrow morning 6 'clock
     * */
    public static int getCloudDataExpireSeconds() {
        DateTime dt = DateTime.now();
        int hours = 24 - dt.getHourOfDay() + 5;
        int minutes = 60 - dt.getMinuteOfHour();

        return 3600 * hours + 60 *  minutes;
    }

    /**
     * datetime of morning 6 'clock
     * */
    public static Date getCyclePoint() {
        DateTime dt = DateTime.now();
        return dt.minusSeconds( dt.getSecondOfDay() ).plusHours( 6 ).toDate();
    }

    public static Date getDateSomeDayAgo(int day) {
        DateTime dt = DateTime.now();
        dt = dt.minusMinutes( dt.getMinuteOfDay() );

        dt = dt.minusDays( day );

        return dt.toDate();
    }

    public static Date getTodayDawnTime() {
        DateTime dt = DateTime.now();
        dt = dt.minusMinutes( dt.getMinuteOfDay() );

        return dt.toDate();
    }

    public static String getDatePartitionSomeDayAgo( int day ) {
        return getDatePartitionSomeDayAgo( new Date(), day );
    }

    public synchronized static String getDatePartitionSomeDayAgo(Date dt, int day) {
        return DT_FORMAT.format(new DateTime( dt ).minusDays(day).toDate());
    }

    /**
     * return d is how many hours ago from now, if d future of now, return -1;
     * */
    public static int getHowManyHourHasGone(Date d) {
        DateTime now = DateTime.now();
        DateTime past = new DateTime( d );

        int hourOfPastYears = 0;
        if ( now.getYear() >= past.getYear() ) {
            hourOfPastYears = ( now.getYear() - past.getYear() ) * 24 * 365;
        } else {
            return -1;
        }

        int hoursOfNow = 24 * now.getDayOfYear() + now.getHourOfDay();
        int hoursOfPast = 24 * past.getDayOfYear() + past.getHourOfDay();

        return hourOfPastYears + ( hoursOfNow - hoursOfPast );
    }

}
